package com.getpebble.android.common.framework.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Trace;
import com.koushikdutta.async.future.Future;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.builder.Builders.IV.F;
import com.sun.mail.imap.IMAPStore;

public class AsyncImageView extends ImageView {
    public static final String TAG = AsyncImageView.class.getSimpleName();
    private Bitmap mBitmap = null;
    private final Handler mHandler = new ImageHandler(Looper.getMainLooper());
    private Future<ImageView> mRequestHandle = null;
    private String mUrl = null;

    private class ImageHandler extends Handler {
        public ImageHandler(Looper looper) {
            super(looper);
        }

        public void handleMessage(Message message) {
            switch (message.what) {
                case IMAPStore.RESPONSE /*1000*/:
                    AsyncImageView.this.performRedraw();
                    return;
                default:
                    super.handleMessage(message);
                    return;
            }
        }
    }

    private void performRedraw() {
        setImageBitmap(this.mBitmap);
    }

    private void sendRedrawMessage() {
        if (!this.mHandler.hasMessages(IMAPStore.RESPONSE)) {
            Message message = new Message();
            message.what = IMAPStore.RESPONSE;
            this.mHandler.sendMessage(message);
        }
    }

    public AsyncImageView(Context context) {
        super(context);
    }

    public AsyncImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AsyncImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void fetch(String url) {
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        if (url == null || url.length() < 1) {
            Trace.error(TAG, "'url' cannot be null!");
        } else if (!url.equals(this.mUrl)) {
            this.mUrl = url;
            cancel();
            this.mRequestHandle = ((F) ((F) Ion.with((ImageView) this).error(17301579)).animateIn(R.anim.fade_in_short)).load(url);
        } else if (this.mBitmap != null) {
            sendRedrawMessage();
        }
    }

    public void cancel() {
        this.mHandler.removeMessages(IMAPStore.RESPONSE);
        if (this.mRequestHandle != null) {
            this.mRequestHandle.cancel(true);
            this.mRequestHandle = null;
        }
        if (this.mBitmap != null) {
            this.mBitmap = null;
        }
    }
}
